package com.aiti.lulian.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardEnterpriseCircleDetailDto;
import com.aiti.lulian.dto.CardEnterpriseCircleDto;
import com.aiti.lulian.dto.CardEnterpriseCircleUserCardDto;
import com.aiti.lulian.dto.CardEnterpriseJoinCircleDto;
import com.aiti.lulian.entity.CardEnterpriseCircle;
import com.aiti.lulian.entity.CardEnterpriseCircleApplication;
import com.aiti.lulian.entity.CardEnterpriseCircleLabel;
import com.aiti.lulian.entity.CardEnterpriseCircleUserCard;
import com.aiti.lulian.entity.newCard.CardBaseInfo;
import com.aiti.lulian.entity.newCard.CardMessage;
import com.aiti.lulian.mapper.CardEnterpriseCircleMapper;
import com.aiti.lulian.mapper.CardEnterpriseCircleUserCardMapper;
import com.aiti.lulian.mapper.newCard.CardMessageMapper;
import com.aiti.lulian.mapper.newCard.CardPersonalBaseInfoMapper;
import com.aiti.lulian.service.CardEnterpriseCircleApplicationService;
import com.aiti.lulian.service.CardEnterpriseCircleLabelService;
import com.aiti.lulian.service.CardEnterpriseCircleService;
import com.aiti.lulian.service.CardEnterpriseCircleUserCardService;
import com.aiti.lulian.vo.CardEnterpriseCircleDetailVo;
import com.aiti.lulian.vo.CardEnterpriseCircleLabelListVo;
import com.aiti.lulian.vo.CardEnterpriseCircleListVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 名片名企圈表 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-08-20
 */
@Service
public class CardEnterpriseCircleServiceImpl extends BaseSerivceImpl<CardEnterpriseCircleMapper, CardEnterpriseCircle> implements CardEnterpriseCircleService {

    @Autowired
    private CardEnterpriseCircleUserCardService circleUserCardService;

    @Autowired
    private CardEnterpriseCircleLabelService circleLabelService;

    @Autowired
    private CardEnterpriseCircleApplicationService cardEnterpriseCircleApplicationService;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;
    @Autowired
    private CardEnterpriseCircleMapper cardEnterpriseCircleMapper;
    @Autowired
    private CardEnterpriseCircleUserCardMapper cardEnterpriseCircleUserCardMapper;
    @Autowired
    private CardMessageMapper cardMessageMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message saveCircle(CardEnterpriseCircleDto dto) {
        String baseId = dto.getBaseId();
        //查询该用户是否是企业管理员

        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(dto.getCardId());
        if(cardBaseInfo == null){
            return Message.fail("名片不存在");
        }
        /** 名片表中版本。1：个人版，2：试用版，3：付费正式版  */
        String cardVersion = cardBaseInfo.getCardVersion();
        Date expireTime = cardBaseInfo.getExpireTime();

        if(StringUtils.isEmpty(cardBaseInfo.getEnterpriseId())){
            return Message.fail("只有企业名片才能创建及修改圈子");
        }
        if(!("3".equals(cardVersion) || "4".equals(cardVersion) || "5".equals(cardVersion))){
            return Message.fail("只有付费名片才能创建及修改圈子");
        }

        if (StringUtils.isEmpty(baseId)) {
//            List<UserCardRoleVo> cardRoleList = cardPersonalBaseInfoMapper.queryUserCardRoleListByCardId(dto.getCardId());
//            if(CollectionUtils.isEmpty(cardRoleList)){
//                return Message.fail("该用户不是企业管理员，不能操作");
//            }else{
//                long adminCount = cardRoleList.stream().filter(f -> "043ea2e3e02c4aa591df1f83e65069bc".equals(f.getRoleId()) || "cc06b294d519480c8a9a62670c416e17".equals(f.getRoleId())).count();
//                if(adminCount <= 0){
//                    return Message.fail("该用户不是企业管理员，不能操作");
//                }
//            }
        } else {
            CardBaseInfo updaterBaseInfo = cardPersonalBaseInfoMapper.selectById(dto.getUpdaterCardId());
            if (updaterBaseInfo == null) {
                return Message.fail("名片不存在");
            }
            CardEnterpriseCircleUserCard circleUserCard = circleUserCardService.getOne(new LambdaQueryWrapper<CardEnterpriseCircleUserCard>().eq(CardEnterpriseCircleUserCard::getCircleId, baseId).eq(CardEnterpriseCircleUserCard::getCardId, dto.getUpdaterCardId()).eq(CardEnterpriseCircleUserCard::getIsDelete, 0));
            if (circleUserCard == null) {
                return Message.fail("非该圈子成员，不能操作");
            }
            if (!("1".equals(circleUserCard.getType()) || "2".equals(circleUserCard.getType()))) {
                return Message.fail("非圈主或主理人，不能操作");
            }
        }

        CardEnterpriseCircle cardEnterpriseCircle = new CardEnterpriseCircle();
        BeanUtils.copyProperties(dto, cardEnterpriseCircle);
        if (StringUtils.isEmpty(baseId)) {
            String number = String.valueOf(RandomUtil.randomInt(10000000, 100000000));
            List<CardEnterpriseCircle> list = this.list(new LambdaQueryWrapper<CardEnterpriseCircle>().eq(CardEnterpriseCircle::getNumber, number));
            while (!CollectionUtils.isEmpty(list)) {
                number = String.valueOf(RandomUtil.randomInt(10000000, 100000000));
                list = this.list(new LambdaQueryWrapper<CardEnterpriseCircle>().eq(CardEnterpriseCircle::getNumber, number));
            }
            cardEnterpriseCircle.setNumber(number);
        }

        if(StringUtils.isEmpty(baseId)){
            cardEnterpriseCircle.setJoinCount(1L);
            cardEnterpriseCircle.setEnterpriseId(cardBaseInfo.getEnterpriseId());
            cardEnterpriseCircle.setCreator(cardBaseInfo.getUserId());
            cardEnterpriseCircle.setCreatorName(cardBaseInfo.getName());
        }

        if (StrUtil.isNotBlank(dto.getUpdaterCardId())) {
            CardBaseInfo updaterBaseInfo = cardPersonalBaseInfoMapper.selectById(dto.getUpdaterCardId());
            cardEnterpriseCircle.setUpdateBy(updaterBaseInfo.getUserId());
            cardEnterpriseCircle.setBaseUpdateTime(new Date());
        }
        this.saveOrUpdate(cardEnterpriseCircle);

        if(StringUtils.isEmpty(baseId)){
            CardEnterpriseCircleUserCard userCard = new CardEnterpriseCircleUserCard()
                    .setCardId(dto.getCardId()).setCircleId(cardEnterpriseCircle.getBaseId())
                    .setInviterCardId(dto.getCardId()).setType("2");
//                    .setCreator(dto.getUserId());
            circleUserCardService.save(userCard);

//            CardEnterpriseCircleUserCardHistory history = new CardEnterpriseCircleUserCardHistory()
//                    .setCardId(dto.getCardId()).setCircleId(cardEnterpriseCircle.getBaseId())
//                    .setInviterCardId(dto.getCardId()).setAuditStatus("2").setCreator(dto.getUserId());
//            userCardHistoryService.save(history);
        }

        List<CardEnterpriseCircleLabel> labelList = dto.getLabelList();
        if (StringUtils.isEmpty(baseId)) {
            if (!CollectionUtils.isEmpty(labelList)) {
                Set<String> seen = new HashSet<>();
                labelList = labelList.stream()
                        .filter(label -> seen.add(label.getLabelName()))
                        .collect(Collectors.toList());
                labelList.forEach(label->{
                    label.setCircleId(cardEnterpriseCircle.getBaseId());
                    label.setEnterpriseId(cardEnterpriseCircle.getEnterpriseId());
                });
                circleLabelService.saveBatch(labelList);
            }
        } else {
            // 查询当前圈子的标签集
            List<CardEnterpriseCircleLabel> circleLabelList = circleLabelService.list(new LambdaQueryWrapper<CardEnterpriseCircleLabel>().eq(CardEnterpriseCircleLabel::getCircleId, baseId).eq(CardEnterpriseCircleLabel::getType, 1));
            // 从传参中过滤 获取到没有发生变动的标签集
            List<CardEnterpriseCircleLabel> noChangeCircleList = labelList.stream().filter(i -> StrUtil.isNotBlank(i.getBaseId())).collect(Collectors.toList());
            // 做差 获取到要移除的标签集
            List<CardEnterpriseCircleLabel> circleLabelCopyList = new ArrayList<>(circleLabelList);
            circleLabelCopyList.removeAll(noChangeCircleList);
            if (!CollectionUtils.isEmpty(circleLabelCopyList)) {
                List<String> failMsgList = new ArrayList<>();
                List<String> secondSureMsgList = new ArrayList<>();
                for (CardEnterpriseCircleLabel label : circleLabelCopyList) {
                    // 移除前校验是否已有圈子成员正在使用该标签
                    int count_1 = circleUserCardService.count(new LambdaQueryWrapper<CardEnterpriseCircleUserCard>().eq(CardEnterpriseCircleUserCard::getLabelId, label.getBaseId()).eq(CardEnterpriseCircleUserCard::getIsDelete, 0));
                    if (count_1 > 0) {
                        failMsgList.add("「" + label.getLabelName() + "」");
                    } else {
                        // 再校验当前是否存在使用该标签申请加入圈子且状态为待审批的申请，若存在需进行二次确认
                        List<CardEnterpriseCircleApplication> circleHistoryList = cardEnterpriseCircleApplicationService.list(new LambdaQueryWrapper<CardEnterpriseCircleApplication>().eq(CardEnterpriseCircleApplication::getLabelId, label.getBaseId()).eq(CardEnterpriseCircleApplication::getStatus, 0));
                        if (circleHistoryList.size() > 0) {
                            if (!(dto.getIsSure() != null && dto.getIsSure())) {
                                secondSureMsgList.add("「" + label.getLabelName() + "」");
                                continue;
                            }
                            // 移除待审批申请中的标签
                            List<CardEnterpriseCircleApplication> updatedCircleHistoryList = circleHistoryList.stream().peek(i -> i.setLabelId(null)).collect(Collectors.toList());
                            cardEnterpriseCircleApplicationService.updateBatchById(updatedCircleHistoryList);
                        }
                        // 移除标签
                        circleLabelService.removeById(label.getBaseId());
                    }
                }
                if (!CollectionUtils.isEmpty(failMsgList)) {
                    return Message.fail("标签" + failMsgList.stream().collect(Collectors.joining("")) + "已被圈子成员使用，移除失败");
                }
                if (!CollectionUtils.isEmpty(secondSureMsgList)) {
                    return new Message(2, "操作失败", "标签" + secondSureMsgList.stream().collect(Collectors.joining("")) + "有加入申请正在使用，请确认是否移除");
                }
            }
            // 从传参中过滤 获取到要新增的标签集
            List<CardEnterpriseCircleLabel> insertedCircleList = labelList.stream().filter(i -> StrUtil.isBlank(i.getBaseId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(insertedCircleList)) {
                insertedCircleList = insertedCircleList.stream().distinct().collect(Collectors.toList());
                insertedCircleList.forEach(label->{
                    label.setCircleId(cardEnterpriseCircle.getBaseId());
                    label.setEnterpriseId(cardEnterpriseCircle.getEnterpriseId());
                });
                circleLabelService.saveBatch(insertedCircleList);
            }
        }

        return Message.success();
    }

    @Override
    public Message circleList(Page page, CardEnterpriseCircleDto dto) {
        List<CardEnterpriseCircleListVo> list = this.getBaseMapper().circlePage(page, dto);
        return Message.success(list);
    }

    @Override
    public Message activeCircleList(Page page, CardEnterpriseCircleDto dto) {
        List<CardEnterpriseCircleListVo> list = this.getBaseMapper().activeCircleList(page, dto);
        return Message.success(list);
    }

    @Override
    public Message detail(CardEnterpriseCircleDetailDto dto) {
        String currentCardId = dto.getCurrentCardId();
        CardBaseInfo visitBaseInfo = cardPersonalBaseInfoMapper.selectById(currentCardId);
        if(visitBaseInfo == null){
            return Message.fail("访问人名片不存在");
        }
        String enterpriseId = visitBaseInfo.getEnterpriseId();
        if(StringUtils.isEmpty(enterpriseId)){
            return Message.fail("访问人名片不是企业名片，只有企业名片才能使用该功能");
        }


        CardEnterpriseCircleDto queryDto = new CardEnterpriseCircleDto();
        queryDto.setBaseId(dto.getBaseId()).setCardId(dto.getCardId()).setNumber(dto.getNumber());
        List<CardEnterpriseCircleListVo> circleList = this.getBaseMapper().circleList(queryDto);
        
        if(CollectionUtils.isEmpty(circleList)){
            return Message.fail("圈子不存在");
        }
        CardEnterpriseCircleListVo circle = circleList.get(0);

        Map map = new HashMap();
        map.put("baseInfo", circle);
        CardEnterpriseCircleDetailDto cardEnterpriseCircleDetailDto = new CardEnterpriseCircleDetailDto();
        //0为圈子普通成员  1为圈子主理人 2为圈子创建人
        cardEnterpriseCircleDetailDto.setBaseId(dto.getBaseId()).setType("2");
        List<CardEnterpriseCircleDetailVo> managerList = this.getBaseMapper().circleListByConditionWithoutLabel(cardEnterpriseCircleDetailDto);

        map.put("manager", !CollectionUtils.isEmpty(managerList) ? managerList.get(0) : new CardEnterpriseCircleDetailVo());

        cardEnterpriseCircleDetailDto.setType("1");
        List<CardEnterpriseCircleDetailVo> coreUserList = this.getBaseMapper().circleListByConditionWithoutLabel(cardEnterpriseCircleDetailDto);
        map.put("coreList", coreUserList);

        cardEnterpriseCircleDetailDto.setType(null).setLimitNum(dto.getLimitNum());
        List<CardEnterpriseCircleDetailVo> recentJoinUserList = this.getBaseMapper().circleListByConditionWithoutLabel(cardEnterpriseCircleDetailDto);
        map.put("recentJoinList", recentJoinUserList);

        List<CardEnterpriseCircleApplication> applyHistoryList = cardEnterpriseCircleApplicationService.list(new LambdaQueryWrapper<CardEnterpriseCircleApplication>().eq(CardEnterpriseCircleApplication::getCircleId, dto.getBaseId()));
        if(!CollectionUtils.isEmpty(applyHistoryList)){
            //申请状态 0待审批 1已拒绝 2已同意
            long waitingAuditCount = applyHistoryList.stream().filter(f -> "0".equals(String.valueOf(f.getStatus())) || "1".equals(String.valueOf(f.getStatus()))).count();
            if(waitingAuditCount > 0){
                map.put("joinCircleStatus", "0");
            }
            long passAuditCount = applyHistoryList.stream().filter(f -> "2".equals(String.valueOf(f.getStatus()))).count();
            if(passAuditCount > 0){
                map.put("joinCircleStatus", "2");
            }


        }else{
            map.put("joinCircleStatus", "-1");
        }

        return Message.success(map);
    }

    @Override
    public Message editCircleIntroduction(CardEnterpriseCircleDto dto) {
        if(StringUtils.isEmpty(dto.getBaseId())){
            return Message.fail("传参错误");
        }
        //查询该用户是否是企业管理员
        CardEnterpriseCircle circle = this.getById(dto.getBaseId());
        if(circle == null){
            return Message.fail("圈子不存在");
        }
        String cardId = dto.getCardId();
        if(StringUtils.isEmpty(cardId)){
            return Message.fail("传参错误，缺少名片id");
        }
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardId);
        if(cardBaseInfo == null){
            return Message.fail("名片不存在");
        }
//        List<UserCardRoleVo> cardRoleList = cardPersonalBaseInfoMapper.queryUserCardRoleListByCardId(cardId);
//        if(CollectionUtils.isEmpty(cardRoleList)){
//            return Message.fail("该用户不是企业管理员，不能操作");
//        }else{
//            long adminCount = cardRoleList.stream().filter(f -> "043ea2e3e02c4aa591df1f83e65069bc".equals(f.getRoleId()) || "cc06b294d519480c8a9a62670c416e17".equals(f.getRoleId())).count();
//            if(adminCount <= 0){
//                return Message.fail("该用户不是企业管理员，不能操作");
//            }
//
//        }
        long adminCount = circleUserCardService.count(new LambdaQueryWrapper<CardEnterpriseCircleUserCard>().eq(CardEnterpriseCircleUserCard::getCircleId, dto.getBaseId()).eq(CardEnterpriseCircleUserCard::getCardId, cardId).in(CardEnterpriseCircleUserCard::getType, "1", "2"));
        if(adminCount > 0){
            CardEnterpriseCircle updateCircle = new CardEnterpriseCircle().setBaseId(dto.getBaseId()).setIntroduction(dto.getIntroduction());
            this.updateById(updateCircle);
            return Message.success();
        }else{
            return Message.fail("该用户不是圈主或者核心成员，不能操作");
        }

    }

    @Override
    public Message circleLabels(String circleId, Integer type) {
        List<CardEnterpriseCircleLabelListVo> list = circleLabelService.circleLabelList(circleId, type);
        return Message.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message saveLabel(CardEnterpriseCircleDto dto) {
        String baseId = dto.getBaseId();
        CardEnterpriseCircle circle = this.getById(baseId);
        List<CardEnterpriseCircleLabel> labelList = dto.getLabelList();
        // 查询当前圈子的标签集
        List<CardEnterpriseCircleLabel> circleLabelList = circleLabelService.list(new LambdaQueryWrapper<CardEnterpriseCircleLabel>().eq(CardEnterpriseCircleLabel::getCircleId, baseId).eq(CardEnterpriseCircleLabel::getType, 2));
        // 从传参中过滤 获取到没有发生变动的标签集
        List<CardEnterpriseCircleLabel> noChangeCircleList = labelList.stream().filter(i -> StrUtil.isNotBlank(i.getBaseId())).collect(Collectors.toList());
        // 做差 获取到要移除的标签集
        List<CardEnterpriseCircleLabel> circleLabelCopyList = new ArrayList<>(circleLabelList);
        circleLabelCopyList.removeAll(noChangeCircleList);
        if (!CollectionUtils.isEmpty(circleLabelCopyList)) {
            List<String> failMsgList = new ArrayList<>();
            List<String> secondSureMsgList = new ArrayList<>();
            for (CardEnterpriseCircleLabel label : circleLabelCopyList) {
                // 移除前校验是否已有圈子成员正在使用该标签
                int count_1 = circleUserCardService.count(new LambdaQueryWrapper<CardEnterpriseCircleUserCard>().eq(CardEnterpriseCircleUserCard::getLabelId, label.getBaseId()).eq(CardEnterpriseCircleUserCard::getIsDelete, 0));
                if (count_1 > 0) {
                    failMsgList.add("「" + label.getLabelName() + "」");
                } else {
                    // 再校验当前是否存在使用该标签申请加入圈子且状态为待审批的申请，若存在需进行二次确认
                    List<CardEnterpriseCircleApplication> circleHistoryList = cardEnterpriseCircleApplicationService.list(new LambdaQueryWrapper<CardEnterpriseCircleApplication>().eq(CardEnterpriseCircleApplication::getLabelId, label.getBaseId()).eq(CardEnterpriseCircleApplication::getStatus, 0));
                    if (circleHistoryList.size() > 0) {
                        if (!(dto.getIsSure() != null && dto.getIsSure())) {
                            secondSureMsgList.add("「" + label.getLabelName() + "」");
                            continue;
                        }
                        // 移除待审批申请中的标签
                        List<CardEnterpriseCircleApplication> updatedCircleHistoryList = circleHistoryList.stream().peek(i -> i.setLabelId(null)).collect(Collectors.toList());
                        cardEnterpriseCircleApplicationService.updateBatchById(updatedCircleHistoryList);
                    }
                    // 移除标签
                    circleLabelService.removeById(label.getBaseId());
                }
            }
            if (!CollectionUtils.isEmpty(failMsgList)) {
                return Message.fail("标签" + failMsgList.stream().collect(Collectors.joining("")) + "已被圈子成员使用，移除失败");
            }
            if (!CollectionUtils.isEmpty(secondSureMsgList)) {
                return new Message(2, "操作失败", "标签" + secondSureMsgList.stream().collect(Collectors.joining("")) + "有加入申请正在使用，请确认是否移除");
            }
        }
        // 从传参中过滤 获取到要新增的标签集
        List<CardEnterpriseCircleLabel> insertedCircleList = labelList.stream().filter(i -> StrUtil.isBlank(i.getBaseId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(insertedCircleList)) {
            insertedCircleList = insertedCircleList.stream().distinct().collect(Collectors.toList());
            insertedCircleList.forEach(label->{
                label.setCircleId(baseId);
                label.setEnterpriseId(circle.getEnterpriseId());
                label.setType(2);
            });
            circleLabelService.saveBatch(insertedCircleList);
        }
        return Message.success("保存成功");
    }

    @Override
    public Message getCircleBaseInfo(String circleId) {
        CardEnterpriseCircle circle = this.getById(circleId);
        if (circle == null) {
            return Message.fail("圈子不存在");
        }
        CardEnterpriseCircleDto cardEnterpriseCircleDto = new CardEnterpriseCircleDto();
        BeanUtils.copyProperties(circle, cardEnterpriseCircleDto);
        List<CardEnterpriseCircleLabel> labelList = circleLabelService.list(new LambdaQueryWrapper<CardEnterpriseCircleLabel>().eq(CardEnterpriseCircleLabel::getCircleId, circleId).eq(CardEnterpriseCircleLabel::getType, 1).eq(CardEnterpriseCircleLabel::getIsDelete, 0));
        cardEnterpriseCircleDto.setLabelList(labelList);
        return Message.success(cardEnterpriseCircleDto);
    }

    @Override
    public List<Map<String, Object>> getMemberList(CardEnterpriseCircleUserCardDto dto, Page<CardEnterpriseCircleUserCard> page) {
        return cardEnterpriseCircleMapper.selectMemberList(dto, page);
    }

    @Override
    public Message setManager(CardEnterpriseCircleUserCardDto dto) {
        circleUserCardService.update(new LambdaUpdateWrapper<CardEnterpriseCircleUserCard>().in(CardEnterpriseCircleUserCard::getBaseId, dto.getBaseIds()).set(CardEnterpriseCircleUserCard::getType, dto.getType()));
        return Message.success("操作成功");
    }

    @Override
    public Message updateAnnouncement(CardEnterpriseCircleDto dto) {
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(dto.getUpdaterCardId());
        if (cardBaseInfo == null) {
            return Message.fail("名片信息失效");
        }

        CardEnterpriseCircle cardEnterpriseCircle = new CardEnterpriseCircle();
        BeanUtils.copyProperties(dto, cardEnterpriseCircle);
        cardEnterpriseCircle.setUpdateBy(cardBaseInfo.getUserId());
        cardEnterpriseCircle.setBaseUpdateTime(new Date());
        this.updateById(cardEnterpriseCircle);
        return Message.success();
    }

    @Override
    public Message joinCircle(CardEnterpriseJoinCircleDto dto) {
        String circleId = dto.getCircleId();
        CardEnterpriseCircle circle = this.getById(circleId);
        if (circle == null) {
            return Message.fail("圈子不存在");
        }
        String currentCardId = dto.getCardId();
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(currentCardId);
        if(cardBaseInfo == null){
            return Message.fail("名片不存在");
        }
        String enterpriseId = cardBaseInfo.getEnterpriseId();
        /** 名片表中版本。1：个人版，2：试用版，3：付费正式版  */
        String cardVersion = cardBaseInfo.getCardVersion();
        Date expireTime = cardBaseInfo.getExpireTime();

        if(StringUtils.isEmpty(enterpriseId)){
            return Message.fail("只有企业名片才能加入圈子");
        }
        if(!("3".equals(cardVersion) || "4".equals(cardVersion) || "5".equals(cardVersion))){
            return Message.fail("只有付费名片才能加入圈子");
        }
        if(expireTime != null && expireTime.getTime() < System.currentTimeMillis()){
            return Message.fail("当前名片已过期，请续费");
        }


        List<CardEnterpriseCircleApplication> applyHistoryList = cardEnterpriseCircleApplicationService.list(new LambdaQueryWrapper<CardEnterpriseCircleApplication>().eq(CardEnterpriseCircleApplication::getCircleId, circleId));
        if(!CollectionUtils.isEmpty(applyHistoryList)){
            //申请状态 0待审批 1已拒绝 2已同意
            long waitingAuditCount = applyHistoryList.stream().filter(f -> "0".equals(String.valueOf(f.getStatus()))).count();
            if(waitingAuditCount > 0){
                return Message.fail("当前名片已经提交过加入圈子申请，请勿重复提交申请");
            }
            long passAuditCount = applyHistoryList.stream().filter(f -> "2".equals(String.valueOf(f.getStatus()))).count();
            if(passAuditCount > 0){
                return Message.fail("当前名片已经是圈子成员了，请勿重复申请");
            }


        }
        CardEnterpriseCircleApplication apply = new CardEnterpriseCircleApplication();
        apply.setCircleId(circleId).setStatus(0).setApplyTime(new Date())
                .setApplyMethod(dto.getApplyMethod()).setShowAvatar(cardBaseInfo.getShowAvatar())
                .setLabelId(dto.getLabelId()).setApplicantCardId(currentCardId).setEnterpriseName(cardBaseInfo.getEnterpriseName())
                .setPositionOne(cardBaseInfo.getPositionOne()).setProfile(dto.getProfile()).setName(cardBaseInfo.getName())
                .setAvatar(cardBaseInfo.getAvatar()).setInviterName(dto.getInviterName()).setInviterCardId(dto.getInviterCardId());
        cardEnterpriseCircleApplicationService.save(apply);

        // 查询申请人的账号
        String username = cardPersonalBaseInfoMapper.selectUsernameByUserId(cardBaseInfo.getUserId());
        // 查询该圈子圈主名片ID
        CardEnterpriseCircleUserCard cardEnterpriseCircleUserCard = cardEnterpriseCircleUserCardMapper.selectOne(new LambdaQueryWrapper<CardEnterpriseCircleUserCard>().eq(CardEnterpriseCircleUserCard::getCircleId, circleId).eq(CardEnterpriseCircleUserCard::getType, "2").eq(CardEnterpriseCircleUserCard::getIsDelete, 0));
        // 向圈主发送成员申请加入的消息
        CardMessage cardMessage = CardMessage.builder().senderCardId(currentCardId).receiverCardId(cardEnterpriseCircleUserCard.getCardId()).
                content(username + (StrUtil.isNotEmpty(cardBaseInfo.getName()) ? ("（" + cardBaseInfo.getName() + "）") : "") + "申请加入您的圈子：" + circle.getBaseName()).source(2).build();
        cardMessageMapper.insert(cardMessage);

        return Message.success();
    }

    @Override
    public Boolean isCircleMember(String cardId, String circleId) {
        CardEnterpriseCircleUserCard circleUserCard = circleUserCardService.getOne(new LambdaQueryWrapper<CardEnterpriseCircleUserCard>().eq(CardEnterpriseCircleUserCard::getCircleId, circleId)
                .eq(CardEnterpriseCircleUserCard::getCardId, cardId).eq(CardEnterpriseCircleUserCard::getIsDelete, 0));
        if (circleUserCard == null) {
            return false;
        } else {
            return !"0".equals(circleUserCard.getType());
        }
    }
}
